# -*- coding: UTF-8 -*-

# Copyright (C) 2009 Daniele Favara.
# Written by Daniele Favara <daniele@zeroisp.com>.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

import os, sys
import simplejson, urllib
from misc import unicode_urlencode

"""
http://code.google.com/intl/it-IT/apis/maps/documentation/geocoding/
http://googlegeodevelopers.blogspot.com/2008/10/geocoding-in-reverse.html
"""

class MapsGoogleCom(object):
    #apy_key=u'ABQIAAAATw59ltFDL-sx11P8_WP6NRQNZk9Iyf_aiMB_Ni0yIfD-UN3HZxR7uFcLuIhccLGY4eXtbrUeQggL_w'

    def __init__(self, apy_key, url="http://maps.google.com/maps/geo",
                port=80, nostrip=False):
        """
        """
        self.apy_key = apy_key
        self.url = url
        self.nostrip = nostrip

    def _get(self, url):
        req = urllib.urlopen(url)
        ret = simplejson.load(req)
        return ret

    def _get_fkey(self, key):
        "CapitalLower --> capital_lower"
        ret = ''
        for index in range(len(key)):
          let = key[index]
          if index == 0:
               let = let.lower()
          else:
              if let.isupper():
                  let = "_%s"%(let.lower())
          ret += let
        return ret


    def _process_resp(self, newresp, resp):
        for key, val in resp.iteritems():
          fkey = self._get_fkey(key)
          if isinstance(val, dict):
              #print "====", fkey
              newresp = self._process_resp(newresp, val)
          else:
              newresp[fkey] = val
        return newresp

    def _get_resp(self, resp):
        ret = []
        if resp.has_key('Placemark'):
          for placemark in resp['Placemark']:
              newresp = {}
              if placemark.has_key('AddressDetails'):
                  accuracy = placemark['AddressDetails']['Accuracy']
                  newresp['accuracy'] =  accuracy
                  newresp = self._process_resp(newresp, placemark['AddressDetails'])
                  if placemark.has_key('address'):
                      newresp['google_address'] = placemark['address']
                  newresp['google_lng'] =  placemark['Point']['coordinates'][0]
                  newresp['google_lat'] =  placemark['Point']['coordinates'][1]
              ret.append(newresp)
        return ret

    def search(self, address, **kw):
        kw['key'] = self.apy_key
        kw['output'] = u'json'
        kw['oe'] = u'utf8'
        kw['q'] = address
        kw['hl'] = 'it'
        url = "%s?%s"%(self.url,unicode_urlencode(kw))
        try:
            if self.nostrip:
                return self._get(url)
            else:
                resp = self._get(url)
                return resp, self._get_resp(resp)
        except:
            raise

    def reverse_search(self, lat, lng, **kw):
        kw['key'] = self.apy_key
        kw['output'] = u'json'
        kw['oe'] = u'utf8'
        kw['hl'] = 'it'
        kw['q'] = "%s,%s"%(lat, lng)
        url = "%s?%s"%(self.url,unicode_urlencode(kw))
        try:
            if self.nostrip:
                return self._get(url)
            else:
                resp = self._get(url)
                return resp, self._get_resp(resp)
        except:
            raise

if __name__ == '__main__':
    apy_key=u'ABQIAAAA1v-Y8xesB0D6cFrC-pMVaxSVXeQZbWitQgsGPwIefe-ERwwiLBTFRfwdeomK_EiCE90kXjc6v6K_Uw'
    q = sys.argv[1:]
    maps = MapsGoogleCom(apy_key)
    from pprint import pprint
    pprint(maps.reverse_search(46.82288,-123.07066)[1])
    #from pprint import pprint
    #ret = maps.search("Via Giovanni Opisso, 16155 Genova GE, Italia")
    #for i in ret[1]:
    #    print
    #    print i['google_address'].encode('utf-8', 'replace')
    #    for k in i:
    #        try:
    #            print k, i[k].encode('utf-8', 'replace')
    #        except:
    #            print k, i[k]

